package com.example.util;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.ImageView;

import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.DrawableCrossFadeFactory;
import com.bumptech.glide.request.transition.Transition;
import com.example.ruihuada.R;

import static com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions.withCrossFade;


public class ImageUtils {


    /**
     * 加载网络图片
     *
     * @param url       url
     * @param imageView imageView
     * @param imageView transformation 转换器
     */
    public static void loadImage(ImageView imageView, String url) {
        if (TextUtils.isEmpty(url)) {
            return;
        }
        Glide.with(imageView.getContext())
                .load(url)
                .apply(new RequestOptions()
                        .dontAnimate()
                        .skipMemoryCache(false)
                        .centerCrop()
                        .placeholder(R.drawable.ic_placeholder)
                        .error(R.drawable.ic_placeholder)
                        .fallback(new ColorDrawable(Color.RED)))
                .into(imageView);
    }

    public static void loadImageWithFade(ImageView imageView, String url) {
        DrawableCrossFadeFactory factory =
                new DrawableCrossFadeFactory.Builder().setCrossFadeEnabled(true).build();
        Glide.with(imageView.getContext())
                .load(url)
                .centerCrop()
                .transition(withCrossFade(factory))
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .placeholder(R.drawable.ic_placeholder)
                .error(R.drawable.ic_placeholder)
                .into(imageView);
    }

    public static void loadImage(ImageView imageView, String url, int placeholder) {
        loadImage(imageView, url, placeholder, false);
    }

    public static void loadImage(ImageView imageView, String url, int placeholder, boolean isGif) {
        if (TextUtils.isEmpty(url)) {
            Glide.with(imageView.getContext())
                    .load(placeholder)
                    .into(imageView);
            return;
        }
        RequestOptions options = new RequestOptions()
                .placeholder(placeholder)
                .skipMemoryCache(false)
                .error(placeholder)
                .fallback(placeholder);

        if (!isGif) {
            options.dontAnimate();

        }
        Glide.with(imageView.getContext())
                .load(url)
                .apply(options)
                .into(imageView);
    }

    public ImageLoad ImageLoad;

    public interface ImageLoad {
        void Ok();
    }

    public void OKLoad(ImageLoad ImageLoad) {
        this.ImageLoad = ImageLoad;
    }

    public void loadImageRes(ImageView imageView, String url) {
        if (TextUtils.isEmpty(url)) {
            return;
        }
        SimpleTarget<Bitmap> simpleTarget = new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                imageView.setImageBitmap(resource);
                ImageLoad.Ok();
            }
        };
        Glide.with(imageView.getContext()).asBitmap().load(url).into(simpleTarget);

    }

    public static void loadImageBitmap(ImageView imageView, Bitmap url) {

        Glide.with(imageView.getContext())
                .load(url)
                .apply(new RequestOptions()
                        .dontAnimate()
                        .skipMemoryCache(false)
                        .error(new ColorDrawable(Color.WHITE))
                        .fallback(new ColorDrawable(Color.RED)))
                .into(imageView);
    }


    public static void loadRes(ImageView imageView, int url) {
        if (url == 0) {
            return;
        }
        Glide.with(imageView.getContext())
                .load(url)
                .apply(new RequestOptions()
                        .diskCacheStrategy(DiskCacheStrategy.NONE)
                        .dontAnimate()
                        .skipMemoryCache(false)
                        .error(new ColorDrawable(Color.WHITE))
                        .fallback(new ColorDrawable(Color.RED)))
                .transition(withCrossFade())
                .into(imageView);
    }

    public static Bitmap viewConversionBitmap(View view, Activity context) {
//        int w = view.getWidth();
//        int h = view.getHeight();
////        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
////        int width = wm.getDefaultDisplay().getWidth();
////        int height = wm.getDefaultDisplay().getHeight();
//
//        Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
//        Canvas c = new Canvas(bmp);
//
//        c.drawColor(Color.WHITE);
//        /** 如果不设置canvas画布为白色，则生成透明 */
//
//        view.layout(0, 0, w, h);
//        view.draw(c);
//
//        return bmp;
        final boolean drawingCacheEnabled = true;
        view.setDrawingCacheEnabled(drawingCacheEnabled);
        view.buildDrawingCache(drawingCacheEnabled);
        final Bitmap drawingCache = view.getDrawingCache();
        Bitmap bitmap;
        if (drawingCache != null) {
            bitmap = Bitmap.createBitmap(drawingCache);
            view.setDrawingCacheEnabled(false);
        } else {
            bitmap = null;
        }
        return bitmap;
    }

    /**
     * 截取scrollview的屏幕     * @param scrollView     * @return
     */
    public static Bitmap getBitmapByView(View view, Activity context) {
//        int h = 0;
//        Bitmap bitmap = null;
//        // 获取scrollview实际高度
//        for (int i = 0; i < scrollView.getChildCount(); i++) {
//            h += scrollView.getChildAt(i).getHeight();
//            scrollView.getChildAt(i).setBackgroundColor(Color.parseColor("#ffffff"));
//        }        // 创建对应大小的bitmap
//        bitmap = Bitmap.createBitmap(scrollView.getWidth(), h, Bitmap.Config.RGB_565);
//        final Canvas canvas = new Canvas(bitmap);
//        scrollView.draw(canvas);
//        return bitmap;
        DisplayMetrics metrics = new DisplayMetrics();
        context.getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int screenWidth = metrics.widthPixels;
        int screenHeight = metrics.heightPixels;
        view.layout(0, 0, screenWidth, screenHeight);
        int measuredWidth = View.MeasureSpec.makeMeasureSpec(view.getWidth(), View.MeasureSpec.EXACTLY);
        int measuredHeight = View.MeasureSpec.makeMeasureSpec(view.getHeight(), View.MeasureSpec.EXACTLY);
        view.measure(measuredWidth, measuredHeight);
        view.layout(0, 0, view.getMeasuredWidth(), view.getHeight());
        return loadBitmapFromView(view);

    }


    public static Bitmap loadBitmapFromView(View view) {
        final boolean drawingCacheEnabled = true;
        view.setDrawingCacheEnabled(drawingCacheEnabled);
        view.buildDrawingCache(drawingCacheEnabled);
        final Bitmap drawingCache = view.getDrawingCache();
        Bitmap bitmap;
        if (drawingCache != null) {
            bitmap = Bitmap.createBitmap(drawingCache);
            view.setDrawingCacheEnabled(false);
        } else {
            bitmap = null;
        }
        return bitmap;
    }


    /**
     * 加载圆形
     *
     * @param url        url
     * @param imageView  imageView
     * @param resourceId id
     */
    public static void loadImageCircle(ImageView imageView, String url, @DrawableRes int resourceId) {
        if (imageView == null) {
            return;
        }
        if (imageView.getContext() == null) {
            return;
        }
        if (TextUtils.isEmpty(url)) {
            Glide.with(imageView.getContext())
                    .load(resourceId)
                    .into(imageView);
            return;
        }
        Glide.with(imageView.getContext())
                .load(url)
                .apply(RequestOptions.circleCropTransform()
                        .placeholder(resourceId)
                        .error(resourceId)
                        .skipMemoryCache(false)
                        .fallback(resourceId)).into(imageView);
    }

    /**
     * 加载圆角
     *
     * @param url       url
     * @param imageView imageView
     */
    public static void loadImageCorners(ImageView imageView, String url, int radius) {
        if (TextUtils.isEmpty(url)) {
            return;
        }
        //设置图片圆角角度
        RoundedCorners roundedCorners = new RoundedCorners(radius);
//通过RequestOptions扩展功能,override:采样率,因为ImageView就这么大,可以压缩图片,降低内存消耗
        RequestOptions options = RequestOptions.bitmapTransform(roundedCorners);
        Glide.with(imageView.getContext())
                .load(url)
                .apply(RequestOptions.circleCropTransform()

                        .error(new ColorDrawable(Color.WHITE))
                        .apply(options)
                        .fallback(new ColorDrawable(Color.RED)))
                .into(imageView);
    }



}
